var Post = function () {

    var basePath = ROOT_PATH + 'upms/post/',
        pagePath = ROOT_PATH + 'pages/upms/post/',
        $dataGrid = null,
        treeId = '#departmentTree',
        $resourceGrid = null,
        $deptTree = null,
        noSelectedMsg = '请选择岗位';


    /**
     * 初始化数据表格
     * @param gridId
     */
    function initGrid(gridId) {
        var gid = gridId || '#grid-data';
        $dataGrid = BsGridUtil.initBsGrid({
            gridId: gid,
            url: basePath + "list",
            singleSelect: true,
            columns: [
                {checkbox: true},
                {field: 'id', title: '岗位编号'},
                {field: 'postCode', title: '岗位编码'},
                {field: 'postName', title: '岗位名称'},
                {field: 'status', title: '状态',formatter:FormUtils.enumFormatter},
                {field: 'createTime', title: '创建时间'},
                {field: 'op',title:"操作",
                formatter: function (val,row) {
                    var html = '';
                    html += '<a href="javascript:Post.edit(' + row.id + ')" class="btn btn-xs btn-primary">编辑</a>'+ "&nbsp;" +
                        '<a href="javascript:Post.assignResource(' + row.id + ')" class="btn btn-xs btn-primary">分配权限</a>';
                    return html;
                    }
                }
            ],
        });

        return $dataGrid;
    }

    /**
     * 给岗位分配权限
     * @param postId 岗位id
     */
    function listResources(postId) {
        //初始化树
        if (postId) {
            //清空所有权限。
            $resourceGrid.bootstrapTable('uncheckAll');
            setDefaultResources(postId);
        } else {
            Dialog.warning(noSelectedMsg);
        }
    }

    /**
     * 勾选岗位默认的权限
     * @param postId 岗位id
     * @param grid 权限树的grid
     */
    function setDefaultResources(postId) {
        //获取岗位拥有的权限。
        $.Ajax({
            container: $resourceGrid,
            defaultResultType: false,
            url: basePath + 'findResourceIds',
            data: {id: postId},
            success: function (data) {
                if (data && data.length > 0) {
                    $resourceGrid.bootstrapTable("checkBy", {field: "id", values: data});
                }
            }
        })
    }

    /**
     * 给岗位分配权限
     * @param postId
     * @param resourceIds
     */
    function assignResource(postId) {
        var zTree, $dialog;

        /**
         * 渲染树
         * @param resourceIds 该角色已选的资源id
         */
        function renderTree(resourceIds) {
            var treeSetting = {
                treeId: '#resourceTree',
                async: {
                    url: ROOT_PATH + 'upms/resource/list',
                },
                check: {
                    enable: true
                },
                callback: {
                    extendsAsyncSuccess: function (_zTree) {
                        $.each(resourceIds, function (i, resourceId) {
                            var node = _zTree.getNodeByParam("id", resourceId);
                            if (node) {
                                _zTree.checkNode(node);
                            }
                        });
                    }
                }
            };
            zTree = Tree.getTree(treeSetting);
        }

        /**
         * 弹出框打开选择页面
         */
        function openModal(data) {
            $.Get(pagePath + 'post-auth.html', function (page) {
                $dialog = $(page);
                $dialog.modal().on('shown.bs.modal', function (e) {
                    renderTree(data);
                    bindAssignEvent();
                });
            });
        }

        /**
         * 绑定提交事件
         */
        function bindAssignEvent() {
            $dialog.find('button.btn-primary').off("click").on("click", function () {
                var nodes = zTree.getCheckedNodes();
                if (nodes && nodes.length > 0) {
                    var resourceIds = [];
                    $.each(nodes, function (i, node) {
                        resourceIds.push(node.id);
                    })
                    setResources(resourceIds);
                } else {
                    Dialog.warning("请选择资源");
                }
            });
            $dialog.modal().on("hidden.bs.modal", function () {
                $dialog.remove();
            });
        }

        /**
         * 保存选择的资源
         */
        function setResources(resourceIds) {
            $.Ajax({
                url: basePath + "setResources",
                method: "post",
                data: {postId: postId, resourceIds: resourceIds},
                container: $dialog,
                success: function () {
                    $dialog.modal('hide');
                    Dialog.success("分配资源成功");
                }
            });
        }

        $.Get(basePath + 'findResourceIds', {id: postId}, function (data) {
            openModal(data);
        });
    }


    /**
     * 保存资源
     */
    function saveResources() {
        var selectedRole = getSelectedPost();
        if (selectedRole) {

            //获取已选择的资源
            var selected = $resourceGrid.treegrid('getSelections');
            var resourceIds = [];
            $.each(selected, function (i, resource) {
                resourceIds.push(resource.id);
            });

            if (!selected) {
                Dialog.confirm("该操作将清空所选岗位的所有权限,请确认是否继续操作", function (r) {
                    assignResource(selectedRole.id, resourceIds);
                })
            } else {
                assignResource(selectedRole.id, resourceIds);
            }
        } else {
            Dialog.warning(noSelectedMsg);
        }
    }


    /**
     * 删除岗位
     */
    function del(id) {
        if (id) {
            Dialog.confirm('确认删除岗位', function (r) {
                $.Ajax({
                    url: basePath + "delete",
                    data: {id: id},
                    success: function () {
                        Dialog.success("删除成功！");
                        reloadDataGrid();
                    }
                });
            });
        } else {
            Dialog.warning(noSelectedMsg);
        }
    }

    /**
     * 编辑
     */
    function edit(id) {
        if (id) {
            $.Get(basePath + 'edit',{postId:id}, function (page) {
                var $dialog = $(page);
                var $form = $dialog.find('form:first');
                $dialog.modal().on('shown.bs.modal', function (e) {
                    $.Get(basePath + 'getVo', {id: id}, function (data) {
                        if (data) {
                            var resourceIds = $form.find("#resourceIds").val();
                            var newResourceIds = [];
                            var dataIntArr = resourceIds.split(",");
                            for (var i = 0; i < dataIntArr.length; i++) {
                                newResourceIds.push(parseInt(dataIntArr[i]));
                            }
                            FormUtils.setValues($form, data.data);
                            $form.find('#deptName').val(data.data.deptName);
                            initDeptGrid($form,data.data.deptId);
                            $resourceGrid = BsGridUtil.initBsTreeGrid({
                                toolbar:"",
                                url: ROOT_PATH + 'upms/resource/list',
                                gridId:"#resourceTreeDg",
                                treeColumn:1,
                                showRefresh:false,
                                columns: [
                                    {field: 'btSelectItem', checkbox:true},
                                    {field: 'id', title:"id",visible:false},
                                    {field: 'name', title:"名称",width:270},
                                    {field: 'icon', title:"图标",formatter:function (val) {
                                            if (val) {
                                                return "<span class='"+ val +"'></span>"
                                            }
                                        }},
                                    {field: 'seq', title:"排序"},
                                    {field: 'type', title:"资源类型",formatter:function(val){
                                            if (val && val == 1){
                                                return "菜单";
                                            }else{
                                                return "资源";
                                            }
                                        }},
                                    {field: 'url', title:"路径",},
                                    {field: 'status', title:"状态",formatter:FormUtils.enumFormatter,cellStyle:function(value,row,index){
                                            if (value && value.code == 2){
                                                return {css:{"color":"red"}}
                                            }else{
                                                return {css:{"color":"blue"}}
                                            }
                                        }},
                                ],
                                onLoadSuccess:function () {
                                    $resourceGrid.bootstrapTable("checkBy",{field: "id", values: newResourceIds});
                                    $($resourceGrid).find("input[type='checkbox']").attr("disabled",true);
                                }
                            });
                            validateForm($form,$dialog);
                        }
                    });
                });
                $dialog.modal().on("hidden.bs.modal", function () {
                    $dialog.remove();
                });
            })
        } else {
            Dialog.warning(noSelectedMsg);
        }
    }

    /**
     * 初始化部门
     * @param deptId
     */
    function initDeptGrid($form,deptId) {
        $deptTree = Organization.initTree(treeId);
        $deptTree.setting.callback.onClick = function (event, treeId, treeNode) {
            var ids = treeNode.id.split("-");
            //1组织2部门3岗位
            var type = parseInt(ids[0]);
            //对应id
            var id = ids[1];
            if (type == 2){
                $form.find("#deptId").val(id);
                var orgIds = treeNode.pid.split("-");
                if (orgIds[0] == 1){
                    $form.find("#orgId").val(orgIds[1]);
                }
            }else{
                Dialog.warning("请选择部门");
            }
        }
        $deptTree.setting.callback.onAsyncSuccess = function (event, treeId, treeNode,nodes) {
            //默认展开节点
            $deptTree.expandAll(true);
            //节点
            if (nodes.length > 0) {
                for(var i = 0;i < nodes.length;i++){
                    var nodeElement = nodes[i].id.split("-");
                    //部门类型
                    if (nodeElement[0] == 2) {
                        //选中部门
                        if (deptId == nodeElement[1]) {
                            var node = $deptTree.getNodeByParam("id", (nodes[i].id));
                            $deptTree.selectNode(node);
                        }
                    }
                }
            }
        }
    }

    /**
     * 刷新表格
     */
    function reloadDataGrid() {
        $dataGrid.bootstrapTable('refresh');
    }

    /**
     * 获取选中部门
     * @param treeId
     * @returns {*}
     */
    function getSelectedNodes() {
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        if (treeObj) {
            return treeObj.getSelectedNodes();
        } else {
            Dialog.warning('请选择节点');
        }
    }


    /**
     * 创建岗位
     */
    function create() {
        $.Get(basePath + 'create', function (data) {
            if (data) {
                var $dialog = $(data);
                var $form = $dialog.find('form:first');
                $dialog.modal().on("shown.bs.modal", function () {
                    $deptTree = Organization.initTree($form.find("#departmentTree"));
                    $deptTree.setting.callback.onClick = function (event, treeId, treeNode) {
                        var ids = treeNode.id.split("-");
                        //1组织2部门3岗位
                        var type = parseInt(ids[0]);
                        //对应id
                        var deptId = ids[1];
                        //如果是部门
                        if (type == 2) {
                            FormUtils.enableForm($form);
                            $form.find('#deptName').text(treeNode.name);
                            $form.find('#deptId').val(deptId);
                        }else{
                            FormUtils.clearForm($form);
                            FormUtils.disableForm($form);
                            $form.find('#deptName').text("");
                        }
                    }
                    $deptTree.setting.callback.onAsyncSuccess = function (event, treeId, treeNode,nodes) {
                        //默认展开节点
                        $deptTree.expandAll(true);
                        FormUtils.disableForm($form);
                        validateForm($form,$dialog);
                    }
                });
            }
        });
    }

    /**
     * @param $dialog
     */
    function validateForm($form,$dialog) {
        FormUtils.validate($form, {
            rules: {
                /*指定需要校验的元素  通过name数据去指定*/
                postName: {
                    maxlength: 15,
                    minlength: 2,
                    required: true
                },
                remark: {
                    maxlength: 50,
                },
                postCode:{
                    maxlength: 15,
                    minlength: 2,
                    required: true
                }
            },
            message:{
                postName:{
                    required:  "请输入岗位名称",
                    maxlength: "最多允许输入15个字符",
                    minlength: "最少输入2个字符"
                },
                remark:{
                    maxlength: "岗位备注最大50个字符",
                },
                postCode:{
                    required:  "请输入岗位编码",
                    maxlength: "最多允许输入15个字符",
                    minlength: "最少输入2个字符"
                },

            },
            submitHandler: function () {
                var data = FormUtils.getFormObj($form);
                var url = basePath;
                if (data.id) {
                    url += "edit";
                } else {
                    url += "create";
                }
                $.Ajax({
                    url: url,
                    data: data,
                    method: "post",
                    container: 'body',
                    success: function () {
                        $dialog.modal('hide');
                        $dataGrid.bootstrapTable('refresh');
                        Dialog.success('操作成功');
                    }
                });
            }
        })
    }

    /**
     * 获取已经选区的岗位
     * @returns {*}
     */
    function getSelectedPost() {
        return $dataGrid.bootstrapTable('getSelections');
    }

    /**
     * 批量删除
     */
    function batchDelete() {
        var selections = getSelectedPost();
        if (selections.length > 0) {
            Dialog.confirm('确认删除岗位', function (r) {
                var postIds = [];
                $.each(selections, function (i, obj) {
                    postIds.push(obj.id);
                });
                $.Ajax({
                    url: basePath + "batchDelete",
                    data: {ids: postIds},
                    success: function () {
                        Dialog.success("删除成功！");
                        reloadDataGrid();
                    }
                });
            });
        } else {
            Dialog.warning(noSelectedMsg);
        }
    }

    return {
        initGrid: initGrid,
        create: create,
        edit: edit,
        batchDelete: batchDelete,
        saveResources: saveResources,
        assignResource: assignResource
    }
}();